<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="系统编号" prop="htCode">
        <el-input
          v-model="queryParams.htCode"
          placeholder="请输入系统编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['hetong:hetong:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['hetong:hetong:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['hetong:hetong:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['hetong:hetong:export']"
        >导出</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="hetongList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="合同主键" align="center" prop="htId" /> -->
      <el-table-column label="系统编号" align="center" prop="htCode" />
       <el-table-column label="合同编号" align="center" prop="htHtcode" />
      <el-table-column label="合同类型" align="center" prop="htTypeStr" />
      <el-table-column label="货主" align="center" prop="htHzClient.cName" />
      <el-table-column label="供货商" align="center" prop="htGhsClient.cName" />
      <el-table-column label="产地" align="center" prop="htChandi" />
      <el-table-column label="申请人" align="center" prop="sysUser.nickName" />
      <el-table-column label="申请时间" align="center" prop="htTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.htTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="htRemark" />
      <el-table-column label="状态" align="center" prop="htFlag" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['hetong:hetong:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['hetong:hetong:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 添加或修改合同管理对话框 -->
    <my-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" size="medium" label-width="100px">
        <el-row type="flex" justify="start" align="top" width="100%">
          <el-col :span="12">
            <el-form-item label="合同编号" prop="htHtcode">
              <el-input v-model="form.htHtcode" placeholder="请输入合同编号" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产地" prop="htChandi">
              <el-input v-model="form.htChandi" placeholder="请输入产地" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="start" align="top" width="100%">
          <el-col :span="12">
            <el-form-item label="货主" prop="htHzid">
              <my-client-select v-model="form.htHzid" clientName="请选择货主" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供货商" prop="htGhsid">
              <my-client-select v-model="form.htGhsid" clientName="请选择供货商" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="start" align="top" width="100%">
          <el-col :span="24">
            <el-form-item label="备注" prop="htRemark">
              <el-input v-model="form.htRemark" type="textarea" placeholder="请输入备注" :maxlength="200"
                show-word-limit :autosize="{minRows: 2, maxRows: 2}" :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row justify="start" align="top" width="100%">
          <el-tabs type="border-card">
            <el-tab-pane>
              <span slot="label"><i class="el-icon-notebook-2"></i>合同明细</span>
              <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                  <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd2">增加明细</el-button>
                </el-col>
              </el-row>
              <el-table border :data="form.erpHetongItemList" style="width: 100%; height:400px;" :row-class-name="tableRowClassName">
                <el-table-column prop="sysDictData.dictLabel" label="名称">
                </el-table-column>
                <el-table-column prop="htModel" label="规格">
                </el-table-column>
                <el-table-column prop="htPrice" label="单价">
                </el-table-column>
                <el-table-column prop="htWeight" label="重量">
                </el-table-column>
                <el-table-column prop="htMoney" label="金额">
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="120">
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      type="text"
                      icon="el-icon-edit"
                      @click="handleUpdate2(scope.row)"
                    >修改</el-button>

                    <el-button
                      size="mini"
                      type="text"
                      icon="el-icon-delete"
                      @click="handleDelete2(scope.row, form.erpHetongItemList)"
                    >删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            <el-tab-pane>
              <span slot="label"><i class="el-icon-paperclip"></i>附件</span>
              <my-file-upload ref="myfileupload" />
            </el-tab-pane>
          </el-tabs>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>

      <my-dialog :title="title2" :visible.sync="open2" width="600px" append-to-body>
        <el-form ref="form2" :model="form2" :rules="rules2" size="medium" label-width="100px">
          <el-form-item label="名称" prop="dictCode">
            <my-dictdata v-model="form2.dictCode" ref="dictDataSelect" dictDataType="ProductName" dictDataName="请选择货品名称" />
          </el-form-item>
          <el-form-item label="规格" prop="htModel">
            <el-input v-model="form2.htModel" placeholder="请输入规格" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
          <el-form-item label="单价(元/吨)" prop="htPrice">
            <el-input-number v-model="form2.htPrice" v-on:change="setMoney()" :precision="2" :step="0.00" :style="{width: '100%'}">
            </el-input-number>
          </el-form-item>
          <el-form-item label="重量(吨)" prop="htWeight">
            <el-input-number v-model="form2.htWeight" v-on:change="setMoney()" :precision="3" :style="{width: '100%'}">
            </el-input-number>
          </el-form-item>
          <el-form-item label="金额(元)" prop="htMoney">
            <el-input-number v-model="form2.htMoney" :precision="2" :style="{width: '100%'}">
            </el-input-number>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm2">保 存</el-button>
          <el-button @click="cancel2">取 消</el-button>
        </div>
      </my-dialog>

    </my-dialog>

  </div>
</template>

<style>
  .el-table .hidden-row {
    display: none;
  }
</style>

<script>
import { listHetong, getHetong, delHetong, addHetong, updateHetong, exportHetong } from "@/api/erp/hetong/hetong";
import MyFileUpload from "@/components/FileUpload/index";

export default {
  name: "Hetong",
  components: {
    MyFileUpload,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 合同管理表格数据
      hetongList: [],
      // 弹出层标题
      title: "",
      // 弹出层标题
      title2: "",
      // 是否显示弹出层
      open: false,
      open2: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        htCode: null,
        htType: null,
        htHzid: null,
        htGhsid: null,
        htChandi: null,
        htHtcode: null,
        userId: null,
        htTime: null,
        htRemark: null,
        htFlag: null
      },
      // 表单参数
      form: {},
      form2: {},
      // 表单校验
      rules: {
        htHtcode: [{
          required: true,
          message: '请输入合同编号',
          trigger: 'blur'
        }],
        htChandi: [{
          required: true,
          message: '请输入产地',
          trigger: 'blur'
        }],
        htHzid: [{
          required: true,
          message: '请选择货主',
          trigger: 'blur'
        }],
        htGhsid: [{
          required: true,
          message: '请选择供货商',
          trigger: 'blur'
        }],
      },
      rules2: {
        dictCode: [{
          required: true,
          message: '请选择货品名称',
          trigger: 'blur'
        }],
        htModel:[{
          required: true,
          message: '请输入规格',
          trigger: 'blur'
        }],
        htPrice:[{
          required: true,
          message: '请输入单价',
          trigger: 'blur'
        }],
        htWeight:[{
          required: true,
          message: '请输入重量',
          trigger: 'blur'
        }],
        htMoney:[{
          required: true,
          message: '请输入金额',
          trigger: 'blur'
        }],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /**是否显示行 */
    tableRowClassName({row, rowIndex}) {
      if (!row.isShow) {
        return 'hidden-row';
      }
      return '';
    },
    /**设置单价*金额 */
    setMoney(){
      this.form2.htMoney = this.form2.htPrice * this.form2.htWeight;
    },
    /** 查询合同管理列表 */
    getList() {
      this.loading = true;
      listHetong(this.queryParams).then(response => {
        this.hetongList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    cancel2() {
      this.open2 = false;
      this.reset2();
    },
    // 表单重置
    reset() {
      this.form = {
        htId: null,
        htCode: null,
        htType: null,
        htHzid: null,
        //明细数组
        erpHetongItemList: [],
        //上传文件数组
        erpHetongFileList: [],
        htGhsid: null,
        htChandi: null,
        htHtcode: null,
        userId: null,
        htTime: null,
        htRemark: null,
        htFlag: null
      };
      this.resetForm("form");
    },
    reset2() {
      this.form2 = {
        tempKeyId:null,
        htParentid: null,
        htId: null,
        sysDictData: null,
        dictCode: null,
        htName: null,
        htModel: null,
        htPrice: null,
        htWeight: null,
        htMoney: null,
        isShow: true
      };
      this.resetForm("form2");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.htId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加合同管理";
    },
    /** 新增按钮操作2 */
    handleAdd2() {
      this.reset2();
      this.open2 = true;
      this.title2 = "添加合同明细";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const htId = row.htId || this.ids
      getHetong(htId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改合同管理";
      });
    },
    /** 修改按钮操作 */
    handleUpdate2(row) {
      this.reset2();
      this.form2 = row;
      this.open2 = true;
      this.title2 = "修改合同明细";
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.htId != null) {
            // updateCaizhi(this.form).then(response => {
            //   this.msgSuccess("修改成功");
            //   this.open = false;
            //   this.getList();
            // });
          } else {
            console.log( this.form );

            if (this.form.erpHetongItemList.length > 0 ){
                var uploadFiles = [];
                this.$refs.myfileupload.fileList.filter(item =>{ 
                  var uploadFileItem = {htFilename: item.name, htFilepath:item.response.url};
                  uploadFiles.push( uploadFileItem );
                });

                this.form.erpHetongFileList = uploadFiles;

                console.log( this.form );

                addHetong(this.form).then(response => {
                  this.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                });
            }else{
              this.msgSuccess("无合同明细无法继续！"); 
            }
          }
        }
      });
    },
    submitForm2() {
      this.$refs["form2"].validate(valid => {
        if (valid) {
          var htitems = {
            tempKeyId: this.form2.tempKeyId,
            htParentid: this.form2.htParentid, 
            htId: this.form2.htId,
            sysDictData: {
              dictCode: this.$refs.dictDataSelect.dictCode, 
              dictLabel: this.$refs.dictDataSelect.dictLabel 
            },
            dictCode: this.$refs.dictDataSelect.dictCode, 
            htModel: this.form2.htMoney,
            htPrice: this.form2.htPrice,
            htWeight: this.form2.htWeight,
            htMoney: this.form2.htMoney,
            isShow: this.form2.isShow,
          } 

          if (this.form2.htId != null) {
            this.form.erpHetongItemList.filter(item =>{ 
                if (item.htId === htitems.htId)
                { 
                  item.htParentid = htitems.htParentid;
                  item.htId = htitems.htId;
                  item.sysDictData = htitems.sysDictData;
                  item.dictCode = htitems.dictCode;
                  item.htModel = htitems.htMoney;
                  item.htPrice = htitems.htPrice;
                  item.htWeight = htitems.htWeight;
                  item.htMoney = htitems.htMoney;
                  item.isShow = htitems.isShow;
                } 
              } 
            );
          }else if (htitems.tempKeyId != null){
            this.form.erpHetongItemList.filter(item =>{ 
                if (item.tempKeyId === htitems.tempKeyId)
                { 
                  item.htParentid = htitems.htParentid;
                  item.htId = htitems.htId;
                  item.sysDictData = htitems.sysDictData;
                  item.dictCode = htitems.dictCode;
                  item.htModel = htitems.htMoney;
                  item.htPrice = htitems.htPrice;
                  item.htWeight = htitems.htWeight;
                  item.htMoney = htitems.htMoney;
                  item.isShow = htitems.isShow;
                } 
              } 
            );
          }else {
            htitems.tempKeyId = this.form.erpHetongItemList.length + 1;
            this.form.erpHetongItemList.push(htitems);
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const htIds = row.htId || this.ids;
      this.$confirm('是否确认删除合同管理编号为"' + htIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delHetong(htIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 删除按钮操作 */
    handleDelete2(row, rows) {
      this.$confirm('是否确认删除名称："' + row.sysDictData.dictLabel + '", 规格"'+row.htMoney+'", 重量："'+row.htWeight+'"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          rows.filter(item =>{ 
            if (item.htId != null){
              if(item.htId === row.htId){
                item.isShow = false;
              }
            }else if (item.tempKeyId != null){
              if (item.tempKeyId === row.tempKeyId){ 
                item.isShow = false;
              }
            }
          });
        }).then(() => {
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有合同管理数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportHetong(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    }
  }
};
</script>

